package com.weds.data_sync.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;

/**
 * @Description 线程池执行器配置
 * @Author lihw
 * @Date 2024/1/9 10:07
 */
@Slf4j
@Configuration
public class ThreadPoolExecutorConfig {

    @Autowired
    private ThreadPoolConfig threadPoolConfig;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        String threadNamePrefix = threadPoolConfig.getThreadNamePrefix();
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        try {
            log.info("开始初始化线程池 -->threadPoolTaskExecutor");
            taskExecutor.setThreadNamePrefix(threadNamePrefix);
            taskExecutor.setCorePoolSize(threadPoolConfig.getCorePoolSize());
            taskExecutor.setMaxPoolSize(threadPoolConfig.getMaxPoolSize());
            taskExecutor.setQueueCapacity(threadPoolConfig.getQueueCapacity());
            // 通过反射获取RejectedExecutionHandlerClass 的类模板
            Class<?> rejectedExecutionHandlerClass = Class.forName(threadPoolConfig.getRejectedExecutionHandler());
            // 获取RejectedExecutionHandlerClass类的实例
            RejectedExecutionHandler rejectedExecutionHandler = (RejectedExecutionHandler) rejectedExecutionHandlerClass.newInstance();
            taskExecutor.setRejectedExecutionHandler(rejectedExecutionHandler);
            taskExecutor.setKeepAliveSeconds(threadPoolConfig.getKeepAliveSeconds());
            // 进行加载
            taskExecutor.initialize();
            log.info("初始化线程池完成:{}核心线程为{}-->", threadNamePrefix, taskExecutor.getCorePoolSize());
            return taskExecutor;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("初始化线程池失败:{}失败原因为:{}", threadNamePrefix, e.getMessage());
            return null;
        }
    }
}
